$('.dayin').on('click', function () {
    $('.layui-header').css('display', 'none')
    $('.layui-side').css('display', 'none')
    $('.left-sidebar').css('display', 'none')
    $('form').parent().css('display', 'none')
    $('.carlist').css('display', 'none')
    $('.orderlist').css('display', 'none')
    $('.tpl-content-wrapper').css('margin', 0)
    $('.am-breadcrumb').css('display', 'none')
    $('.car_date').css('display', 'none')
    $('.button-group').css('display', 'none')
    $('.layui-body').css('top', '0')
    $('.layui-body').css('left', '0')
    $('#map').height('700px')
    $('#map').width('1200px')
    setTimeout(function () {
        window.print()
    }, 500)
    if (tata = document.execCommand("print")) {
        window.history.go(0)
    }
})
AMapUI.loadUI([
    'control/BasicControl',
    'overlay/SimpleMarker',
    'overlay/SimpleInfoWindow',
    'misc/PathSimplifier'
], function (BasicControl, SimpleMarker, SimpleInfoWindow, PathSimplifier) {
    let py;
    if ($.cookie("area") == 2) {
        py = [0, 0]
    } else {
        py = [-2.782459, +3.9238951]
    }
    $('.qiehuan').on('click', function () {
        console.log($.cookie("area"))
        if ($.cookie("area") == 2) {
            $.cookie("area", '1', { path: '/' });
        } else {
            $.cookie("area", '2', { path: '/' });
        }
        window.history.go(0)
    })
    let map = new AMap.Map('map', {
        resizeEnable: true,
        zoom: 10,
        center: qd
    });
    let origin = {
        car: [], //车辆
        order: [], //订单
        interest: [] //兴趣点
    }
    //兴趣点图片
    let imgarr = ['{$static_dir}/assets/img/house-yellow.png',
        '{$static_dir}/assets/img/house-red.png',
        '{$static_dir}/assets/img/house-greed.png',
        '{$static_dir}/assets/img/house-blue.png',
    ]
    //地图插件
    let layerCtrl1 = new BasicControl.LayerSwitcher({
        position: 'tr'
    });

    //车辆列表滚动
    let myScroll = new IScroll('.carlist-list', {
        mouseWheel: true,
        disableMouse: true,
        scrollbars: true
    });
    //订单列表滚动
    let myScroll_order = new IScroll('.orderlist-list', {
        mouseWheel: true,
        disableMouse: true,
        scrollbars: true
    });
    map.setStatus({
        layers: layerCtrl1.getEnabledLayers()
    });
    map.addControl(layerCtrl1);
    let infoWindow;
    let trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10
    });
    trafficLayer.setMap(map);
    trafficLayer.hide();

    let cluster = []; //点聚合
    let id, orderid, ordercont;
    //搜索
    poi_search(map)  //关键字搜索
    //行政区域
    var district, polygons = [], citycode;
    var citySelect = document.getElementById('city');
    var districtSelect = document.getElementById('district');
    var areaSelect = document.getElementById('street');
    var opts = {
        subdistrict: 1,   //返回下一级行政区
        showbiz: false  //最后一级返回街道信息
    };
    district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
    district.search('中国', function (status, result) {
        if (status == 'complete') {
            getData(result.districtList[0]);
        }
    });
    $('#province').on('change', function () {
        search(this)
    })
    $('#city').on('change', function () {
        search(this)
    })
    $('#district').on('change', function () {
        search(this)
    })
    $('#street').on('change', function () {
        setCenter(this)
    })
    function getData(data, level) {
        var bounds = data.boundaries;
        if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
                var polygon = new AMap.Polygon({
                    map: map,
                    strokeWeight: 1,
                    strokeColor: '#CC66CC',
                    fillColor: '#CCF3FF',
                    fillOpacity: 0.5,
                    path: bounds[i]
                });
                polygons.push(polygon);
            }
            map.setFitView();//地图自适应
        }



        //清空下一级别的下拉列表
        if (level === 'province') {
            citySelect.innerHTML = '';
            districtSelect.innerHTML = '';
            areaSelect.innerHTML = '';
        } else if (level === 'city') {
            districtSelect.innerHTML = '';
            areaSelect.innerHTML = '';
        } else if (level === 'district') {
            areaSelect.innerHTML = '';
        }

        var subList = data.districtList;
        if (subList) {
            var contentSub = new Option('--请选择--');
            var curlevel = subList[0].level;
            var curList = document.querySelector('#' + curlevel);
            curList.add(contentSub);
            for (var i = 0, l = subList.length; i < l; i++) {
                var name = subList[i].name;
                var levelSub = subList[i].level;
                var cityCode = subList[i].citycode;
                contentSub = new Option(name);
                contentSub.setAttribute("value", levelSub);
                contentSub.center = subList[i].center;
                contentSub.adcode = subList[i].adcode;
                curList.add(contentSub);
            }
        }

    }
    function search(obj) {
        //清除地图上所有覆盖物
        for (var i = 0, l = polygons.length; i < l; i++) {
            polygons[i].setMap(null);
        }
        var option = obj[obj.options.selectedIndex];
        var keyword = option.text; //关键字
        var adcode = option.adcode;
        district.setLevel(option.value); //行政区级别
        district.setExtensions('all');
        //行政区查询
        //按照adcode进行查询可以保证数据返回的唯一性
        district.search(adcode, function (status, result) {
            if (status === 'complete') {
                getData(result.districtList[0], obj.id);
            }
        });
    }
    function setCenter(obj) {
        map.setCenter(obj[obj.options.selectedIndex].center)
    }


    //工具
    tool(map, trafficLayer)
    //右击
    rightclick(map, imgarr, origin, table)






    //地图所需字段
    let iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');

	$('.company_name').on('click', function () {
        opsearch('/html/system/company?op=search')
    })

    let path = {};
    ajaxcar({})
    $('.backcar').on('click', function () {
        $('.carlist ul').html("")
        $('.orderlist ul').html("")
        map.clearMap();
        ajaxcar({})
    })
    //车辆
    //车辆请求
    function ajaxcar(cardata) {
        $('.carlist').css('display', 'block');
        $('.orderlist').css('display', 'none');
        $('.car_date').css('display', 'none');
        ajax('{$static_dir}/assets/json/beidou_car.json', cardata, 'get').done((res) => {
        	Load(1)
            if (typeof res == 'string') {
                res = JSON.parse(res)
            }
			for(var where_i=0;where_i<res.data.length;where_i++){
			//本地数据搜索
				{if $Think.get.car_state}
				if(res.data[where_i].state=='{$Think.get.car_state}'){}else{
					res.data.splice(where_i,1)
					where_i--
				}
				{/if}
			}
            res.data = beidou_state(res.data)
            origin.car = res.data;
            console.log(res)
            console.log(res)

            for (let car_i = 0; car_i < origin.car.length; car_i++) {
                if (origin.car[car_i].loc[0]) {
                    origin.car[car_i].loc[0] = origin.car[car_i].loc[0] + (py[0] - 0)
                    origin.car[car_i].loc[1] = origin.car[car_i].loc[1] + (py[1] - 0)
                    addcar(origin.car[car_i])
                    carlist(origin.car[car_i], 1, car_i)
                    //车辆地图节点点击
                    origin.car[car_i].point.on('click', function () {
                        let car_id = get_obj_val($(this), 'car_id');
                        clear_car(origin.car, car_id) //清除地图上的车辆节点
                        let orderdata = {
                            car_id: car_id
                        };
                        ajaxorder(orderdata,2)
                    })
                    //车辆地图节点移入
                    origin.car[car_i].point.on('mouseover', function () {
                        let car_id_arr = [];
                        car_id_arr.push($(this)[0].opts.cont.car_id)
                        let car_detail = get_search_car(origin.car, car_id_arr)[0]
                        openmessage(1, car_detail, 1)
                    })
                    //车辆地图节点移出
                    origin.car[car_i].point.on('mouseout', function () {
                        let car_id_arr = [];
                        car_id_arr.push($(this)[0].opts.cont.car_id)
                        let car_detail = get_search_car(origin.car, car_id_arr)[0]
                        openmessage(2, car_detail, 1)
                    })

                } else {
                    carlist(origin.car[car_i], 2, car_i)
                }
            }
            cluster = addCluster(2, origin, cluster)
            //车辆列表展示
            $('.carlist ul li').on('click', function () {
            	clearorder(origin.order)
                for (let car_list_i = 0; car_list_i < origin.car.length; car_list_i++) {
                    if (origin.car[car_list_i].number == $(this).find('.number').html()) {
                        clear_car(origin.car, origin.car[car_list_i].car_id)
                        let orderdata = {
                            car_id: origin.car[car_list_i].car_id
                        };
                        ajaxorder(orderdata,2)
                    }
                }
            })
            myScroll.refresh()
        }).fail(() => { })
    };
    //添加车辆地图节点
    function addcar(obj) {

        let pointimg = '';
        if (obj.state == 1) {
            if (obj.state_run == 1) {
                pointimg = '{$static_dir}/assets/img/car-greed.png';
            } else {
                pointimg = '{$static_dir}/assets/img/car-yellow.png';
            }

        } else if (obj.state == 2) {
            pointimg = '{$static_dir}/assets/img/car-red.png';
        };
        let str = new RegExp('黄', "i");
        let number_background = '';
        if (obj.number.match(str)) {
            number_background = 'yellow'
            number_color = '#000'
        } else {
            number_background = 'blue'
            number_color = '#fff'
        }
        obj.point = new SimpleMarker({
            //普通文本
            iconStyle: {
                src: pointimg,
                style: {
                    width: '15px',
                    height: '30px'
                }
            },
            position: obj.loc,
            label: {
                content: `<div style='background:${number_background};width:100%;height:100%;color:${number_color};padding:3px;'>${obj.number}<div>`,
                offset: new AMap.Pixel(-25, 34)
            },
            cont: {
                car_id: obj.car_id,
                number: obj.number
            }
        });
        obj.point.setMap(map);
    };
    //列表添加车辆节点
    function carlist(obj, type, i) {
        let locclss = '';
        if (type == 1) {
            locclss = 'layui-icon-location'
        } else { }
        $('.carlist ul').append(
            `
			<li class="layui-text layui-row">
				<div class="layui-col-sm2" style="">
					<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${i + 1}</div>
				</div>
				<div class = "layui-col-sm10 ">
					<div class = "layui-col-sm6  am-text-truncate" style="font-size:12px">
					<span class='number'>${obj.number}</span>
					<i class='layui-icon ${locclss}' style='color:red'></i>
					</div>
					<div class='layui-col-sm6' style="font-size:12px">${obj.state_name}</div>
				</div>
			</li>`
        );
    };
    //清除除了所需的节点以外的所有车辆节点
    function clear_car(cararr, car_id) {
        cluster.clearMarkers()
        for (let i = 0; i < cararr.length; i++) {
            if (cararr[i].point) { //判断是否存在地图节点
                if (cararr[i].car_id == car_id) { //判断是否为点击得到地图节点
                	if(cararr[i].loc[0]){
	                    addcar(cararr[i])
	                    cararr[i].point.on('click',function(){
	                    	 let car_id = get_obj_val($(this), 'car_id');
	                        clear_car(origin.car, car_id) //清除地图上的车辆节点
	                        let orderdata = {
	                            car_id: car_id
	                        };
	                        ajaxorder(orderdata,2)
	                    })
	                    //车辆地图节点移入
	                     cararr[i].point.on('mouseover', function () {
	                        let car_id_arr = [];
	                        car_id_arr.push($(this)[0].opts.cont.car_id)
	                        let car_detail = get_search_car(origin.car, car_id_arr)[0]
	                        openmessage(1, car_detail, 1)
	                    })
	                    //车辆地图节点移出
	                     cararr[i].point.on('mouseout', function () {
                        let car_id_arr = [];
                        car_id_arr.push($(this)[0].opts.cont.car_id)
                        let car_detail = get_search_car(origin.car, car_id_arr)[0]
                        openmessage(2, car_detail, 1)
                    })
                	}
                } else {
                    map.remove(cararr[i].point); //删除地图节点
                }
            } else {
                if (cararr[i].car_id == car_id) {
                    Err('该车辆无定位')
                }
            }
        }


    }
    //添加车辆点聚合
    //点聚合
    function addCluster(tag, origin, cluster, markers) {

        markers = []
        var _renderCluserMarker = function (context) {
            var factor = Math.pow(context.count / count, 1 / 18)
            var div = document.createElement('div');
            var Hue = 180 - factor * 180;
            var bgColor = 'hsla(' + Hue + ',100%,50%,0.7)';
            var fontColor = 'hsla(' + Hue + ',100%,20%,1)';
            var borderColor = 'hsla(' + Hue + ',100%,40%,1)';
            var shadowColor = 'hsla(' + Hue + ',100%,50%,1)';
            div.style.backgroundColor = bgColor
            var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
            div.style.width = div.style.height = size + 'px';
            div.style.border = 'solid 1px ' + borderColor;
            div.style.borderRadius = size / 2 + 'px';
            div.style.boxShadow = '0 0 1px ' + shadowColor;
            div.innerHTML = context.count;
            div.style.lineHeight = size + 'px';
            div.style.color = fontColor;
            div.style.fontSize = '14px';
            div.style.textAlign = 'center';
            context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
            context.marker.setContent(div)
        }
        for (var maidx = 0; maidx < origin.car.length; maidx++) {
            if (origin.car[maidx].point) {
                markers.push(origin.car[maidx].point)
            }
        }
        var count = markers.length;
        if (cluster[0]) {
            cluster.setMap(null);
        }
        if (tag == 2) { //完全自定义
            cluster = new AMap.MarkerClusterer(map, markers, {
                gridSize: 30,
                renderCluserMarker: _renderCluserMarker,
                maxZoom: 17,
                zoomOnClick: false
            });
        } else if (tag == 1) { //自定义图标
            var sts = [{
                url: "http://a.amap.com/jsapi_demos/static/images/blue.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -16)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/green.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -16)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/orange.png",
                size: new AMap.Size(36, 36),
                offset: new AMap.Pixel(-18, -18)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/red.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24)
            }, {
                url: "http://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24)
            }];
            cluster = new AMap.MarkerClusterer(map, markers, {
                styles: sts,
                gridSize: 30,
                maxZoom: 17
            });
        } else { //默认样式
            cluster = new AMap.MarkerClusterer(map, markers, {
                gridSize: 30,
                maxZoom: 17
            });

        }
        cluster.on('click', function (obj) {
            var car_list_detail = [];
            for (let i = 0; i < obj.markers.length; i++) {
                for (let i1 = 0; i1 < origin.car.length; i1++) {
                    if (origin.car[i1].car_id == obj.markers[i].opts.cont.car_id) {
                        car_list_detail.push(origin.car[i1])
                    }

                }
            }
            var car_list_detail_w = {
                data: car_list_detail
            }
            car_list_detail_w = driverstate(car_list_detail_w)
            car_list_detail = car_list_detail_w.data
            var clustertable = `<table class="layui-table">`
            clustertable +=
                `<theader>
						<th>车牌号</th>
						<th>司机</th>
						<th>经纬度</th>
						<th>状态</th>
				</theader>
				<tbody>`
            for (var ii = 0; ii < car_list_detail.length; ii++) {
                clustertable +=
                    `<tr>
						<td>${car_list_detail[ii].number}</td>
						<td>${car_list_detail[ii].driver_name ? car_list_detail[ii].driver_name : '王吉艺'}</td>
						<td>${car_list_detail[ii].loc}</td>
						<td>${car_list_detail[ii].state_name}</td>
					<tr>`
            }
            clustertable += `</table>`
            layer.open({
                type: 1,
                title: false,
                skin: 'layui-layer-rim', //加上边框
                area: ['750px', '300px'], //宽高
                content: `<div style="padding:10px">
				  						${clustertable}
				  					</div>`,
                success: function () {

                }
            });
        })
        return cluster
    }




    //订单
    //订单请求
    function ajaxorder(orderdata,type22) {
        origin.order = [];
//      $('.carlist').css('display', 'none');
//      $('.orderlist').css('display', 'block');
//      $('.car_date').css('display', 'block');
        Load()
        ajax('{$static_dir}/assets/json/beidou_order.json', orderdata, 'get').done((res) => {
        	 $('.orderlist ul').html("")
            if (typeof res == 'string') {
                res = JSON.parse(res)
            }
            Load(1)
            for (let key in res) {
                if (res[key].car_id == orderdata.car_id) {
                    origin.order.push(res[key])
                }
            }
            console.log('dingdanshu')
            console.log(origin.order)
            let obj = {};
            obj.data = origin.order
            origin.order = orderstate(obj).data
            for (let order_i = 0; order_i < origin.order.length; order_i++) {
                if (origin.order[order_i].from_lon) {
                    origin.order[order_i].from_lon = origin.order[order_i].from_lon - 0 + (py[0] - 0)
                    origin.order[order_i].from_lat = origin.order[order_i].from_lat - 0 + (py[1] - 0)
                }
                addorder(origin.order[order_i], order_i) //添加订单地图节点
//              orderlist(origin.order[order_i], order_i) //添加订单列表节点
				
                myScroll_order.refresh()

                origin.order[order_i].point.on('click', function (res) {
                    let order_id = $(this)[0].opts.cont.order_id;
                    ajaxpath(order_id)
                });
                //订单地图节点移入
                origin.order[order_i].point.on('mouseover', function () {
                   let order_detail1 = {}
                    for(var order_ii=0;order_ii<origin.order.length;order_ii++){
                        if(origin.order[order_ii].order_id==$(this)[0].opts.cont.order_id){
                            order_detail1=origin.order[order_ii]
                        }
                    }
                    openmessage(1, order_detail1, 2)
                })
                //车辆地图节点移出
                origin.order[order_i].point.on('mouseout', function () {
                    let order_detail1 = {}
                    for(var order_ii=0;order_ii<origin.order.length;order_ii++){
                        if(origin.order[order_ii].order_id==$(this)[0].opts.cont.order_id){
                            order_detail1=origin.order[order_ii]
                        }
                    }
                    openmessage(2, order_detail1, 2)
                })

            }
            if(type22){
            	popuporder(origin.order)
            }
             //订单弹出框
             
            $('.orderlist ul li').on('click', function () {

                ajaxpath($(this).data('id'))
            })
        }).fail(() => {
            Load(1)
        })
    };
    //添加订单地图节点
    function addorder(obj, i) {
        obj.path = [];
        obj.path.push(obj.from_lon - 0);
        obj.path.push(obj.from_lat - 0);



        obj.point = new SimpleMarker({
            //普通文本
            iconStyle: iconStyles[2],
            //图标文字
            iconLabel: {
                //A,B,C.....
                innerHTML: i + 1,
                style: {
                    color: '#fff'
                }
            },
            map: map,
            position: obj.path,
            path: obj.path,
            cont: {
                order_id: obj.order_id
            }
        });
        obj.point.setMap(map);
    };
    //列表添加订单节点
    function orderlist(obj, i) {
        $('.orderlist ul').append(
            `
		<li data-id='${obj.order_id}' >
			<div class="layui-col-sm2" style="padding:5px;">
				<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${i + 1}</div>
			</div>
			<div class = "layui-col-sm6 cl-p">
				<div class = "layui-col-sm12 cl-p am-text-truncate" style="font-size:12px">${obj.orders_time}</div>
				<div class = "layui-col-sm12 cl-p am-text-truncate" style="font-size:12px">${obj.complete_time ? obj.complete_time : '-'}</div>
			</div>
            <div class="layui-col-sm3 " >
				<div class = "layui-col-sm12 cl-p am-text-truncate" style="font-size:12px;text-align:center">${obj.order_state2}</div>
				<div class = "layui-col-sm12 cl-p am-text-truncate star" style="font-size:12px;">
                    ${showstar(5)}
                </div>
			
			</div>
	    </li>`
        );

    };
    //弹出该车的订单
    function popuporder(obj){
    	let objarr=[];
    	if(obj){
    		if(obj.length>10){
    		  for(var obj_i=0;obj_i<10;obj_i++){
    		  	objarr.push(obj[obj_i])
    		  }
    		}
    	}
    	layer.open({
			type: 1,
			title: '订单列表',
			skin: 'layui-layer-rim', //加上边框
			area: ['80%', '80%'], //宽高
			content: `
					<div>
					<div style='padding:10px'>
		  				<table class='layui-hide' id='order_car' lay-filter="order_car"></table>
		  				<div id='page'></div>
		  			</div>
		  			
					</div>`,
			success: function() {
				let fi=1;
				console.log(obj)
				let main1=[[ //表头
					{field:'order_no', width:200,title: '订单号', templet: '#orderNo', fixed: 'left'}
			        ,{field: 'apply_time',width:180, title: '申请时间',  sort: true}
			        ,{field: 'approval_time',width:180, title: '批准时间'} 
			        ,{field: 'orders_time',width:180, title: '接单时间'}
			        ,{field: 'order_type2', width:100, title: '订单类型', sort: true}
			        ,{field:'orderer', width:100,title:'申请人'}
			        ,{field:'approval',width:100, title:'审核人'}
			     	,{field:'use_type2',width:100, title:'用车类型'}
			        ,{field:'use_explain',width:100, title:'用车说明'}
			        ,{field:'order_state2', title:'订单状态'}
			       ,{ title: '操作',width:80, toolbar:'#operation',fixed: 'right'}
			       ]];
			         table.render({
					  	elem: '#order_car'
					    ,cellMinWidth: 80
					    ,cols: main1
						,data: objarr
						,limit: 1000
						,even: true
					});
					
					table.on('tool(order_car)', function(obj){
						var data2 = obj.data; //获得当前行数据
						 var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
						 var tr = obj.tr; //获得当前行 tr 的DOM对象
						 if(layEvent === 'path') {
						 	ajaxpath(data2.order_id)
						 }
 					})
			    
			}
		});
    }
    function showstar(star) {
        var stardiv = `<div style='height:20px;width:110px;overflow:hide'>`
        if (star <= 5) {
            for (let i = 0; i < star; i++) {
                stardiv += `<img src='{$static_dir}/assets/img/star-on.png' style='width:20px;height:20px;float:left'/>`
            }
        }
        stardiv += `</div>`
        return stardiv
    }
    function clearorder(orderarr, order_id) {
        for (let i = 0; i < orderarr.length; i++) {
            if (orderarr[i].point) { //判断是否存在地图节点
                map.remove(orderarr[i].point);
            } else {
                if (cararr[i].order_id == order_id) {
                    Err('该订单起点无定位')
                }
            }
        }
    }

    //轨迹
    function ajaxpath(order_id) {
       var index = layer.load(0, {
		  shade: [0.1,'#fff'] //0.1透明度的白色背景
		});
        ajax('{$static_dir}/assets/json/beidou_path.json', {}, 'get').done((res) => {
            Load(1)
            if (typeof res == 'string') {
                res = JSON.parse(res)
            }
            console.log(res)
            let is_has_path = 0
            for (let path_i = 0; path_i < res.length; path_i++) {
                if (res[path_i].order_id == order_id) {
                    path = res[path_i];
                    is_has_path = 1
                }
            }
            if (is_has_path == 0) {
                path = res[0]
            }
            let allpath = [];
            let opath1 = path.data;
            let opath2 = [];
            let opath = [];
            console.log(path)
            if (opath1.length > 1) {
                for (let rankidx = 0; rankidx < opath1.length; rankidx++) {
                    opath2.push(opath1[rankidx].time);
                }
                opath2.sort();
                for (let k = 0; k < opath2.length; k++) {
                    for (let j = 0; j < opath1.length; j++) {
                        if (opath2[k] == opath1[j].time) {
                            opath.push(opath1[j]);
                        }
                    }
                }
                for (let oi = 0; oi < opath.length; oi++) {
                    let oarr = [];
                    oarr.push(opath[oi].longitude);
                    oarr.push(opath[oi].latitude);
                    allpath.push(oarr);
                }
            }
            let order_detail;
            for (var idx = 0; idx < origin.order.length; idx++) {
                if (origin.order[idx].order_id == order_id) {
                    order_detail = origin.order[idx]
                }
            }
            if (order_detail) {
                initPage(allpath, order_detail)
            } else {
                initPage(allpath)
            }
        }).fail()
    }


    //规划路径
    function getpath(obj, map, driving) {
        let arr;
        let content;

        for (let index in obj) {
            for (let index1 in obj[index]) {
                if (index1 == "cont") {
                    idx = index;
                    arr = obj[index].path;
                    content = obj[index].cont;
                };
            };
        };
        let iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');

        //设置数据
        driving.search(new AMap.LngLat(arr[0][0], arr[0][1]), new AMap.LngLat(arr[arr.length - 1][0], arr[arr.length -
            1][1]));
        map.setZoomAndCenter(13, arr[arr.length - 1]);
    };

    //轨迹
    function initPage(path, order_detail) {
        console.log('lujing')
        console.log(path)
        console.log(order_detail)
        order_detail.time='3小时';
        order_detail.speed='60km/h';
        AMap.plugin('AMap.Geocoder', function () {
            geocoder = new AMap.Geocoder({
                city: "010" //城市，默认：“全国”
            });
            geocoder.getAddress(path[0], function (status, result) {

                if (status === 'complete' && result.info === 'OK') {
                    //获得了有效的地址信息:
                    order_detail.from_add = result.regeocode.formattedAddress;
                } else {
                    order_detail.from_add = "获取地址失败";
                }
                geocoder.getAddress(path[1], function (status1, result1) {

                    if (status1 === 'complete' && result1.info === 'OK') {
                        //获得了有效的地址信息:
                        order_detail.to_add = result1.regeocode.formattedAddress;
                    } else {
                        order_detail.to_add = "获取地址失败";
                    }
               
                    let show_order_detail = {
                        mileage: '行驶公里数',
                        speed: '平均车速',
                        time: '用时',
                        from_add: '出发地',
                        to_add: '目的地'
                    }
                    for (var ii = 0; ii < path.length; ii++) {
                        path[ii][0] = path[ii][0] + (py[0] - 0)
                        path[ii][1] = path[ii][1] + (py[1] - 0)
                    }
                    var path_detail = ` <div class='po_absolute' style='padding:10px;z-index:9999;top:0;right:0;width:200px;height:220px;overflow:auto;background:rgba(255,255,255,0.6)'>`
                    for (var key in show_order_detail) {
                        path_detail += `<div>${show_order_detail[key]}：${order_detail[key] ? order_detail[key] :''}</div>`
                    }
                    path_detail += `</div>`
                    let navg0;
                    layer.open({
                        type: 1,
                        title: '订单轨迹回放',
                        skin: 'layui-layer-rim', //加上边框
                        area: ['70%', '70%'], //宽高
                        content: `<div class='prop_map_w po_relative' style='height:100%'>
                                    ${path_detail}
                        
                    
                                        <div id='propmap' style='height:100%'></div>
                                        <div class="button-group">
                                            <input type="button" class="button" value="开始动画" id="start"/>
                                            <input type="button" class="button" value="暂停动画" id="pause"/>
                                                <input type="button" class="button" value="继续动画" id="resume"/>
                                            <input type="button" class="button" value="停止动画" id="stop"/>
                                        </div>
                                        <div id="progress">
                                            <div id="progress_bg">
                                                <div id="progress_bar"></div>
                                            </div>
                                            <div id="progress_btn"></div>
                                        </div>
                                    </div>`,
                        success: function () {
                            let propmap = new AMap.Map("propmap", {
                                resizeEnable: true,
                                center: path[0],
                                zoom: 10
                            });
                            //创建轨迹实例
                            //总路径

                            //正常行驶
                            let pathSimplifierIns_1 = new PathSimplifier({
                                zIndex: 100,
                                map: propmap, //所属的地图实例
                                autoSetFitView: false,
                                getPath: function (pathData, pathIndex) {
                                    //返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
                                    return pathData.path;
                                },
                                getHoverTitle: function (pathData, pathIndex, pointIndex) {
                                    //返回鼠标悬停时显示的信息
                                    if (pointIndex >= 0) {
                                        //鼠标悬停在某个轨迹节点上
                                        return '正常行驶<br/>速度:60km/h<br/>里程数:60km<br/>行驶时长:1小时<br/>停车时长：30分钟<br/>'
                                        // return pathData.name + '，点:' + pointIndex + '/' + pathData.path
                                        //     .length;
                                    }
                                    //鼠标悬停在节点之间的连线上
                                    // return pathData.name + '，点数量' + pathData.path.length;
                                    return '正常行驶<br/>速度:60km/h<br/>里程数:60km<br/>行驶时长:1小时<br/>停车时长：30分钟<br/>'
                                },
                                renderOptions: {
                                    //轨迹线的样式
                                    pathLineStyle: {
                                        strokeStyle: 'red',
                                        lineWidth: 6,
                                        dirArrowStyle: true
                                    }
                                }
                            });
                            //超速行驶
                            let pathSimplifierIns_2 = new PathSimplifier({
                                zIndex: 100,
                                map: propmap, //所属的地图实例
                                autoSetFitView: false,
                                getPath: function (pathData, pathIndex) {
                                    //返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
                                    return pathData.path;
                                },
                                getHoverTitle: function (pathData, pathIndex, pointIndex) {
                                    //返回鼠标悬停时显示的信息
                                    if (pointIndex >= 0) {
                                        //鼠标悬停在某个轨迹节点上
                                        // return pathData.name + '，点:' + pointIndex + '/' + pathData.path
                                        //     .length;
                                        return '超速行驶<br/>速度:80km/h<br/>里程数:60km<br/>行驶时长:1小时<br/>停车时长：30分钟<br/>'
                                    }
                                    //鼠标悬停在节点之间的连线上
                                    // return pathData.name + '，点数量' + pathData.path.length;
                                    return '超速行驶<br/>速度:80km/h<br/>里程数:60km<br/>行驶时长:1小时<br/>停车时长：30分钟<br/>'
                                },
                                renderOptions: {
                                    //轨迹线的样式
                                    pathLineStyle: {
                                        strokeStyle: 'orange',
                                        lineWidth: 6,
                                        dirArrowStyle: true
                                    }
                                }
                            });
                            let pathSimplifierIns_all = new PathSimplifier({
                                zIndex: 100,
                                map: propmap, //所属的地图实例
                                getPath: function (pathData, pathIndex) {
                                    //返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
                                    return pathData.path;
                                },
                                getHoverTitle: function (pathData, pathIndex, pointIndex) {
                                    //返回鼠标悬停时显示的信息
                                    if (pointIndex >= 0) {
                                        //鼠标悬停在某个轨迹节点上
                                        // return pathData.name + '，点:' + pointIndex + '/' + pathData.path
                                        //     .length;
                                    }
                                    //鼠标悬停在节点之间的连线上
                                    // return pathData.name + '，点数量' + pathData.path.length;
                                },
                                renderOptions: {
                                    //轨迹线的样式
                                    pathLineStyle: false
                                }
                            });
                            let path1 = [], path2 = []
                            for (let i = 0; i < path.length; i++) {
                                if (i < path.length / 2) {
                                    path1.push(path[i])
                                } else {
                                    path2.push(path[i])
                                }
                            }
                            // 

                            pathSimplifierIns_1.setData([{
                                name: '轨迹0',
                                path: path1
                            }]);
                            pathSimplifierIns_2.setData([{
                                name: '轨迹0',
                                path: path2
                            }]);
                            pathSimplifierIns_all.setData([{
                                name: '轨迹0',
                                path: path
                            }]);
                            //创建一个巡航器
                            navg0 = pathSimplifierIns_all.createPathNavigator(0, //关联第1条轨迹
                                {
                                    loop: false, //循环播放
                                    speed: 1000,
                                    content: PathSimplifier.Render.Canvas.getImageContent('{$static_dir}/assets/img/car-red.png', onload, onerror)
                                });

                            // 轨迹更能按钮
                            navg0.start();
                            $('#start').on('click', function () {
                                navg0.start()
                            });
                            $('#pause').on('click', function () {
                                navg0.pause()
                            });
                            $('#resume').on('click', function () {
                                navg0.resume()
                            });
                            $('#stop').on('click', function () {
                                navg0.stop()
                            });
                            navg0.on('move', function () {
                                let left = (navg0.getCursor().idx / path.length) * 300
                                $('#progress_btn').css('left', left);
                                $('#progress_bar').css('width', left);
                            })


                            //拖动
                            //滚动条
                            let tag = false,
                                ox = 0,
                                left = 0,
                                bgleft = 0
                            AMap.event.addDomListener(document.getElementById('progress_btn'), 'mousedown',
                                function (e) {
                                    ox = e.pageX - left;
                                    tag = true;
                                }, false);
                            $(document).mouseup(function () {
                                tag = false;
                            });
                            AMap.event.addDomListener(document.getElementById('progress'), 'mousemove',
                                function (e) {
                                    if (tag) {
                                        left = e.pageX - ox;
                                        if (left <= 0) {
                                            left = 0;
                                        } else if (left > 300) {
                                            left = 300;
                                        }
                                        $('#progress_btn').css('left', left);
                                        $('#progress_bar').width(left);
                                        let num = Math.floor(left / tip) - 1;
                                        if (num < 0) {
                                            num = 0
                                        } else {
                                            num = Math.ceil(left / tip);
                                        }
                                        let progress_br = left / 300

                                        navg0.moveToPoint(parseInt(path.length * progress_br))
                                    }
                                }, false);
                            AMap.event.addDomListener(document.getElementById('progress_bg'), 'click', function (
                                e) {
                                if (!tag) {
                                    bgleft = $('#progress_bg').offset().left;
                                    left = e.pageX - bgleft;
                                    if (left <= 0) {
                                        left = 0;
                                    } else if (left > 300) {
                                        left = 300;
                                    }
                                    $('#progress_btn').css('left', left);
                                    $('#progress_bar').animate({
                                        width: left
                                    }, 300);
                                    let progress_br = left / 300
                                    navg0.moveToPoint(parseInt(path.length * progress_br))
                                }
                            }, false);
                            // 

                        }, end: function (index, layero) {
                            navg0.destroy()
                        }
                    })
                });
            });

        })



    }

    //打开信息框
    //type 展示的是车辆信息还是订单信息（1为车辆，2为订单）
    function openmessage(isopen, obj, type) {
        if (isopen == 1) {
            if (type == 1) { //判断是否显示的是车辆的信息
                let info = ``;
                AMap.plugin('AMap.Geocoder', function () {
                    geocoder = new AMap.Geocoder({
                        city: "010" //城市，默认：“全国”
                    });
                    geocoder.getAddress(obj.loc, function (status, result) {
                        info += `<div>`;
                        info += `<h2 style='color:#1E9FFF'>${obj.number}</h2>`;
                        info += `<p>经纬度:${obj.loc}</p>`;
                        info += `<p>乘坐人:${obj.passenger_name ? obj.passenger_name : '林富麒'}</p>`;
                        info += `<p>驾驶人:${obj.driver_name ? obj.driver_name : '王名杏'}</p>`;
                        info += `<p>速度:${obj.speed ? obj.speed : '60km/h'}</p>`;
                        info += `<p>方向:${obj.direction ? obj.direction : '东南'}</p>`;
                        info += `<p>定位时间:${obj.time}</p>`;
                        info += `<p>定位类型:北斗</p>`;
                        info += `<p>车辆状态:${obj.state_name}</p>`;
                        if (status === 'complete' && result.info === 'OK') {
                            //获得了有效的地址信息:
                            address = result.regeocode.formattedAddress;
                        } else {
                            address = "获取地址失败";
                        }
                        info += `<p>地理位置:${address}</p>`;
                        info += `</div>`;
                        infoWindow = new AMap.InfoWindow({
                            content: info, //使用默认信息窗体框样式，显示信息内容
                            offset: new AMap.Pixel(0, -25)
                        });
                        infoWindow.open(map, obj.point.getPosition());
                    });

                })
            } else if (type == 2) {
                let info = ``;
                AMap.plugin('AMap.Geocoder', function () {
                    geocoder = new AMap.Geocoder({
                        city: "010" //城市，默认：“全国”
                    });
                    geocoder.getAddress([obj.from_lon, obj.from_lat], function (from_status, from_result) {
                        let address_from = '';
                        if (from_status === 'complete' && from_result.info === 'OK') {
                            address_from = from_result.regeocode.formattedAddress;

                        } else {
                            address_from = "获取地址失败";
                        }
                        let address_to = ';'
                        info += `<div>`;
                        info +=
                            `<h2 style='color:#1E9FFF'>${obj.order_no}</h2>`;
                        info += `<p>下单人:${obj.orderer}</p>`;
                        info += `<p>审批人:${obj.orderer ? obj.orderer : '高燕'}</p>`;
                        info += `<p>乘客:${obj.passenger_name ? obj.passenger_name : '陈兴南'}</p>`;
                        info += `<p>司机:${obj.driver_name ? obj.driver_name : '郭劲彬'}</p>`;
                        info += `<p>订单类型:${obj.use_type2}</p>`;
                        info += `<p>订单状态:${obj.order_state2}</p>`;

                        info += `<p>出发地:${address_from}</p>`;
                        info += `</div>`;
                        infoWindow = new AMap.InfoWindow({
                            content: info, //使用默认信息窗体框样式，显示信息内容
                            offset: new AMap.Pixel(0, -25)
                        });
                        infoWindow.open(map, obj.point.getPosition());
                        //获得了有效的地址信息:


                    });

                })
            }
        } else {
            if (infoWindow) {
                infoWindow.close()
            }

        }

    }

})
